import tkinter as tk
from tkinter import filedialog, ttk
from PIL import Image, ImageTk
import os
from tkinter import messagebox


def select_output_path():
    global output_path
    output_path = filedialog.askdirectory()
    if output_path:
        output_path_label.config(text=output_path)


def select_image():
    global image_path, image, photo, suffix
    image_path = filedialog.askopenfilename(filetypes=[("JPEG Files", ".jpg"), ("PNG Files", "*.png")])
    if image_path:
        image = Image.open(image_path)
        photo = ImageTk.PhotoImage(image)
        width = image.size[0]
        height = image.size[1]
        suffix = os.path.splitext(image_path)[1]
        # 比例缩放
        if width > 500 or height > 500:
            ratio = min(500 / width, 500 / height)
            width = int(width * ratio)
            height = int(height * ratio)
            image = image.resize((width, height))
            photo = ImageTk.PhotoImage(image)
        image_label.config(image=photo)


def compress_image():
    global image_path, output_path, image
    if not image_path:
        messagebox.showwarning("警告", "请先选择图片！")
        return
    if not output_path:
        messagebox.showwarning("警告", "请先选择输出位置！")
        return

    target_size_kb = int(size_entry.get())
    target_width = int(width_entry.get())
    target_height = int(height_entry.get())

    # 计算压缩比例
    ratio = min(target_width / image.size[0], target_height / image.size[1])

    # 计算压缩后的尺寸
    new_width = int(image.size[0] * ratio)
    new_height = int(image.size[1] * ratio)

    # 压缩图片
    compressed_image = image.resize((new_width, new_height))

    # 设置保存路径
    save_path = ""
    # 转换格式
    format_suffix = format_combobox.get()
    if format_suffix == ".png":
        save_path = os.path.join(output_path, "compressed_image.png")
        compressed_image = compressed_image.convert("RGBA")
    elif format_suffix == ".jpg":
        save_path = os.path.join(output_path, "compressed_image.jpg")
        compressed_image = compressed_image.convert("RGB")
    # 保存压缩后的图片
    compressed_image.save(save_path)

    messagebox.showinfo("提示", "图片压缩完成！保存路径：" + save_path)


# 创建GUI窗口
window = tk.Tk()
window.title("图片压缩工具-By:小娟佩奇")
window.geometry("1080x900")

# 添加输出位置选择按钮
output_path_button = tk.Button(window, text="选择输出位置", command=select_output_path)
output_path_button.pack()
# 展示输出位置
output_path_label = tk.Label(window, text="输出位置：")
output_path_label.pack()

# 添加图片选择按钮
select_image_button = tk.Button(window, text="选择图片", command=select_image)
select_image_button.pack()

# 添加图片展示框
image_label = tk.Label(window)
image_label.pack()

# 添加目标大小输入框和标签
size_label = tk.Label(window, text="图片大小（KB）：")
size_label.pack()
# 默认值为190KB
size_entry = tk.Entry(window)
size_entry.pack()
size_entry.insert(0, "190")

# 添加宽度输入框和标签
width_label = tk.Label(window, text="图片宽度（px）：")
width_label.pack()
width_entry = tk.Entry(window)
width_entry.pack()
width_entry.insert(0, "300")

# 添加高度输入框和标签
height_label = tk.Label(window, text="图片高度（px）：")
height_label.pack()
height_entry = tk.Entry(window)
height_entry.pack()
height_entry.insert(0, "400")
# 添加图片输出格式
format_label = tk.Label(window, text="图片格式：")
format_label.pack()
# 下拉框
format_entry = tk.StringVar()
format_combobox = tk.ttk.Combobox(window, textvariable=format_entry)
format_combobox.pack()
format_combobox["value"] = [".png", ".jpg"]
format_combobox.current(1)

# 添加压缩按钮
compress_button = tk.Button(window, text="压缩", command=compress_image)
compress_button.pack()

# 启动事件循环
window.mainloop()
